<template>
  <div>
    <!-- //Breadcrumb面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- car卡片 -->
    <el-card class="box-card">
      <!--搜索与添加区域 layout布局  ----- 行 -->
      <el-row :gutter="40">
        <!-- layout布局  ----- 第一列 -->
        <el-col :span="7">
          <!-- 搜索框 -->
          <el-input placeholder="请输入内容" clearable @clear="getUserMessage()" v-model="querInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserMessage()"></el-button>
          </el-input>
        </el-col>
        <!-- layout布局  ----- 第二列 -->
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible = true">
            添加用户
          </el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" style="width: 100%" border>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="setChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="200">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-tooltip effect="dark" content="修改信息"  placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="amendUserMage(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUserMage(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配权限 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="quanxianUserMage(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="cleaFromData('add')">
      <!-- 内容主题区域 -->
      <el-form :model="addFrom" :rules="FromRules" ref="addFromRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFrom.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">
          <!--@click="dialogVisible = false" -->
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户信息" @close="cleaFromData('xuigai')" :visible.sync="amendUser" width="50%">
      <el-form ref="amendForm" :rules="FromRules" :model="xiuGaiUser">
        <el-form-item label="姓名">
          <el-input v-model="xiuGaiUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="xiuGaiUser.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="xiuGaiUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="amendUser = false">取 消</el-button>
        <el-button type="primary" @click="amendUserOK">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配新角色 -->
    <el-dialog title="分配权限" :visible.sync="fenpei_quanxian" width="50%"  @close="cleaFromData('fenpei')">
      <div>当前的用户：{{fenpei.username}}</div>
      <div>当前的角色：{{fenpei.role_name}}</div>
      <!-- <div>分配新角色:
        <el-select placeholder="请选择" v-model="rolesList">
          <el-option label="itemList" value="shanghai"  v-for="(itemList,i) in rolesList" :key="i"></el-option>
        </el-select>
      </div> -->
      <div>
        分配新角色:
        <el-select v-model="selectValue" placeholder="请选择">
          <el-option v-for="itemList in rolesList" :key="itemList.id" :label="itemList.roleName" :value="itemList.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fenpei_quanxian = false">取 消</el-button>
        <el-button type="primary" @click="fenpei_quanxianOK">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    //自定义电话的校验规则
    var checkMobile = (rule, value, callback) => {
      //手机号的正则表达式
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号！！！"));
    };
    return {
      querInfo: {
        query: "",
        //当前展示的页数
        pagenum: 1,
        pagesize: 5,
      },
      userList: [],
      // total为总页数
      total: 0,

      //控制对话框 显示与隐藏
        dialogVisible: false, //加用户对话框
        amendUser: false, //修改用户对话框
        fenpei_quanxian:false,  //分配权限对话框

      //添加用户的表单数据
      addFrom: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //编辑用户表单数据
      xiuGaiUser: {
        username: "",
        id: "",
        mobile: "",
        email: "",
      },

      //角色分配中所用到的数据
      fenpei:{},
      //角色分配中的数据列表
      rolesList:[],
      //select下拉列表的v-model值
      selectValue:"",

      //表单验证规则对象
      FromRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 1, max: 5, message: "长度在 1 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //从数据库中读取数据
    async getUserMessage() {
      // console.log("@@@", this.$http);
      const { data: res } = await this.$http.get("users", {
        params: this.querInfo,
      });
      // console.log("@@@@@@@", res);
      if (res.meta.status != 200) {
        return this.$message.error("获取用户列表失败，原因是：" + res.meta.msg);
      }
      this.userList = res.data.users;
      this.total = res.data.total;
    },

    // 监听 pagesize(即那个下拉框默认的值) 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize);
      this.querInfo.pagesize = newSize;
      this.getUserMessage(); //渲染完以后重新请求一下服务器
    },

    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage);
      this.querInfo.pagenum = newPage;
      this.getUserMessage();
    },

    //  监听Switch开关的状态
    async setChange(newChange) {
      // console.log(newChange);
      const { data: res } = await this.$http.put(
        `users/${newChange.id}/state/${newChange.mg_state}`
      );
      if (res.meta.status != 200) {
        newChange.mg_state = !newChange.mg_state; //虽然修改到数据库中失败了  但是在页面表面 还是修改了 所以要改回去
        return this.$message.error(
          "修改错误！！！！！     原因为：" + res.meta.msg
        );
      }
      this.$message({
        showClose: true,
        message: "修改成功！！！！",
        type: "success",
      });
    },

    //点击确定提交事件（先进行预验证，成功就进行axio数据库写入，然后再清空对话框 关闭对话框）
    addUser() {
      //往数据库中提交时先进行预验证
      this.$refs.addFromRef.validate(async (boolean) => {
        if (boolean) {
          //进行axio的数据写入
          const { data: res } = await this.$http.post("users", this.addFrom);
          if (res.meta.status != 201) {
            return this.$message.success(
              "数据库写入失败！！！！   原因是",
              res.meta.msg
            );
          }
          this.dialogVisible = false; //关闭对话框
          this.getUserMessage(); //添加数据库成功后，重新请求一边数据渲染到页面上
          return this.$message.success("提交成功,成功写入数据库！！！！");
        } else {
          return this.$message.error("请输入正确格式后在进行提交");
        }
      });
    },

    //点击修改信息按钮，进行一系列操作
    async amendUserMage(aaa) {
      this.amendUser = true; //打开对话框
      const { data: vv } = await this.$http.get(`users/${aaa}`); //请求这一行的数据
      this.xiuGaiUser.id = vv.data.id; //进行id赋值
      this.xiuGaiUser.username = vv.data.username; //进行姓名赋值
      this.xiuGaiUser.email = vv.data.email; //进行邮箱赋值
      this.xiuGaiUser.mobile = vv.data.mobile; //进行手机赋值
    },

    //点击修改信息对话框中的确认按钮后  进行更新数据
    amendUserOK() {
      //先校验
      this.$refs.amendForm.validate(async (errr) => {
        if (errr) {
          // 校验成功，可以传数据库
          const { data: res } = await this.$http.put(
            `users/${this.xiuGaiUser.id}`,
            this.xiuGaiUser
          );
          //对返回来的数据进行判断  是否更新成功
          if (res.meta.status) {
            console.log(res.data);
            this.$message.success(res.meta.msg); //更新正确提示
            this.getUserMessage(); //重新请求一遍数据渲染到页面上
            this.amendUser = false; //关闭对话框
          } else {
            //更新失败的提示
            this.$message({
              showClose: true,
              message: res.meta.msg + "错误代号为：" + res.meta.state,
              type: "error",
            });
          }
        } else {
          this.$message({
            showClose: true,
            message: "预校验出错！！！",
            type: "error",
          });
        }
      });
    },

    //点击删除按钮进行删除操作
    deleteUserMage(aaa) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "删除用户", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: deleteRes } = await this.$http.delete(`users/${aaa}`); //点击确定后发送删除信息请求
          if (deleteRes.meta.status != 200) {
            console.log(deleteRes);
            this.$message.error(
              "删除失败！！  错误原因为：" + deleteRes.meta.msg
            );
          } else {
            this.$message({
              type: "success",
              message: "删除成功!",
            }),
              this.getUserMessage(); //删除完毕后重新请求数据渲染一遍页面
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //点击分配角色
    async quanxianUserMage(aaa){

      //打开对话框的第一件事  将当前角色的信息保存起来 进行页面显示
      this.fenpei = aaa;

      //进行axios请求  将角色的所有权限显示出来
      const {data:fess} = await this.$http.get("roles");
      if(fess.meta.status === 200){
        this.rolesList = fess.data;
      }else{
        this.$message.error("请求角色列表失败！！！"+fess.meta.status)
      }
      //打开分配角色对话框
      this.fenpei_quanxian = true;
    },

     //分配权限对话框 点击“确定”之后一系列操作
    async fenpei_quanxianOK(){
      //发送axios请求 进行分配用户角色
      const {data:fes} = await this.$http.put(`users/${this.fenpei.id}/role`,{rid:this.selectValue});
      if(fes.meta.status == 200){
        this.$message.success(fes.meta.msg);
        this.getUserMessage();
      }else{
        this.$message.error("设置角色失败！！！！"+fes.meta.status);
      }
      //关闭对话框
      this.fenpei_quanxian = false;
    },


    //关闭对话框进行 清空对话框中的数据操作（即重置表单）  ------  所有的对话框关闭都在此操作
    cleaFromData(a) {
      console.log(a);
      if(a === "add"){
        this.$refs.addFromRef.resetFields();
      }
      if(a === "xuigai"){
        this.$refs.amendForm.resetFields();
      }
      if(a === "fenpei"){
        //清空下拉列表选中数据暂存区
        this.selectValue = "";
        //清空角色分配中所用到的数据
        this.fenpei = {};
        //清空角色分配中的数据列表
        this.rolesList = [];
      }
    },
  },




  created() {
    this.getUserMessage();
  },
};
</script>

<style scoped>
.box-card {
  box-shadow: -5 5 20 rgba(0, 0, 0, 0.3) !important;
}
.el-dialog__body div:nth-child(2),
.el-dialog__body div:nth-child(3){
  margin-top: 20px;
}

</style>